package com.et.drive.run


import com.et.drive.info.*
import com.et.drive.out.ICashSelectionImpl
import com.et.drive.out.IOutGoodsImpl
import com.et.logger.ELog
import com.et.logger.TAGS
import com.et.protocol.ano.Act2Code
import com.et.protocol.ano.Act3Code
import com.et.protocol.core.ETInlets
import com.et.protocol.core.IGuide
import com.et.protocol.core.IObserver
import java.io.File
import java.util.concurrent.Executors

const val DEFAULT_PORT = "ttymxc1"

object Run {

    private val thread = Executors.newSingleThreadExecutor()
    private val guides = HashMap<String, IGuide>()

    fun openPort(p: String = DEFAULT_PORT) {
        thread.execute {
            if (guides.containsKey(p)) {
                ELog.d(TAGS.machine, "$p exist")
            } else {
                ELog.d(TAGS.machine, "$p create new instance")
                val file = File("/dev/$p")
                guides[p] = ETInlets.Builder()
                    .configPortName(file.absolutePath)
                    .configObserver(Observer)
                    .build().apply {

                    }
            }
        }
    }

    fun getGuide(port: String = DEFAULT_PORT): IGuide? {
        return guides[port]
    }

}

/**
 * TODO mul observer to fit double board
 */
object Observer : IObserver {

    override fun action1(code: Int) {

    }

    override fun action2(code: Int, data: ByteArray) {
        when (code) {
            Act2Code.ACT_08 -> {
                IMachineSignInfoImpl.machineInfoNotify(data)
            }
            Act2Code.ACT_0c -> {
                IOutGoodsImpl.outResultNotify(data)
            }
            Act2Code.ACT_01 -> {
                IMachineIdInfoImpl.machineIdInfoNotify(data)
            }
            Act2Code.ACT_06 -> {
                ICashSelectionImpl.cashSelectionNotify(data)
            }
            Act2Code.ACT_0d -> {
                IMachineOperationInfoImpl.machineOperationInfoNotify(data)
            }

        }
    }

    override fun action3(code: Int, data: ByteArray) {
        when (code) {
            Act3Code.ACT_09 -> {
                IChannelInfoImpl.channelRunningInfoNotify(data)
            }
            Act3Code.ACT_0a -> {
                ILightTemperatureImpl.lightTemperatureInfoNotify(data)
            }
            Act3Code.ACT_0e -> {
                IChannelInfoImpl.channelGoodsIDNotify(data)
            }
            Act3Code.ACT_0f -> {
                IChannelInfoImpl.channelPriceNotify(data)
            }
        }
    }
}

object TaskSignIn {
    fun go(byteArray: ByteArray) {
        ELog.d(TAGS.machine, "${byteArray.toString()}")
    }
}